/**
 * @(#)HttpGetCaller.java 2016年11月3日
 * Copyright(C) 2015 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.httpclient;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.jsbd.boss.exception.ParamNullException;
import org.jsbd.boss.httpclient.vo.Request;
import org.jsbd.boss.httpclient.vo.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * get请求
 * 
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
public class HttpGetCaller extends HttpCaller {

	public static final Logger LOGGER = LoggerFactory.getLogger(HttpGetCaller.class);

	private HttpGet httpGet;
	private Request request;

	public HttpGetCaller(Request request) {
		super(request);
		this.request = request;
	}

	/**
	 * 
	 * doGet:get请求
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @return
	 */
	public Response doGet() {
		if (request == null) {
			throw new ParamNullException("请求参数为空!");
		}
		String url = request.getUrl();
		if (StringUtils.isBlank(url)) {
			throw new ParamNullException("请求地址为空!");
		}
		Response result = new Response();
		CloseableHttpResponse response = null;
		try {
			// 初始化httpget
			httpGet = new HttpGet(buildGetUri());
			LOGGER.info("Executing request {}", httpGet.getRequestLine());
			httpGet.setConfig(buildRequestConfig());
			// 访问头信息
			builderGetHeaders();
			// 发起get请求
			response = httpclient.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			result.setStatus(statusCode);
			if (statusCode == HttpURLConnection.HTTP_OK) {
				result.setSuccess(true);
				result.setHeaders(response.getAllHeaders());
			} else {
				result.setSuccess(false);
				LOGGER.warn("http response status code is not 200. status line: {}" + statusLine);
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String res = EntityUtils.toString(entity);
				result.setData(res);
			} else {
				LOGGER.warn("Response contains no content");
			}
		} catch (Exception e) {
			result.setSuccess(false);
			LOGGER.error("http call error", e);
		} finally {
			if (httpGet != null) {
				httpGet.abort();
			}
			try {
				if (response != null) {
					response.close();
				}
			} catch (Exception e) {
				LOGGER.error("", e);
			}
			try {
				if (httpclient != null) {
					httpclient.close();
				}
			} catch (Exception e) {
				LOGGER.error("链接关闭失败", e);
			}
		}
		return result;
	}

	/**
	 * 
	 * builderHeaders:访问头信息
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 */
	private void builderGetHeaders() {
		Map<String, String> headers = request.getHeaders();
		if (headers != null && !headers.isEmpty()) {
			String[] keys = headers.keySet().toArray(new String[0]);
			for (String key : keys) {
				String value = headers.get(key);
				if (StringUtils.isNotBlank(value)) {
					httpGet.addHeader(new BasicHeader(key, headers.get(key)));
				}
			}
		}
	}

	/**
	 * 
	 * buildUri:初始化请求uri
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @return
	 * @throws URISyntaxException
	 */
	private URI buildGetUri() throws URISyntaxException {
		String url = request.getUrl();
		Map<String, String> params = request.getParams();
		URIBuilder builder = new URIBuilder(url);
		if (params != null && !params.isEmpty()) {
			String[] keys = params.keySet().toArray(new String[0]);
			for (String key : keys) {
				String value = params.get(key);
				if (StringUtils.isNotBlank(value)) {
					builder.addParameter(key, value);
				}
			}
		}
		return builder.build();
	}

}
